package com.yonyou.gmcc.gateway.wechat.controller.message;

import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.util.CookieSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yonyou.gmcc.gateway.wechat.service.interfaces.CustomerServiceInterface;
import com.yonyou.gmcc.gateway.wechat.util.JwtOpenidHelper;

import io.jsonwebtoken.Claims;

@Controller
public class ThirdPortController {

    @Autowired
    private Environment env;
    @Autowired CustomerServiceInterface customerServiceInterface;
    
	private static Logger logger=Logger.getLogger(ThirdPortController.class);

	@RequestMapping("/thirdport")
    public String thirdport(@RequestParam("token") String token) throws Exception{
		logger.info("----------------thirdport token="+token);
		String dm=env.getProperty("wechat.domain");
		Claims claims=JwtOpenidHelper.parseJWT(token);
		String openid=JwtOpenidHelper.getOpenId(claims);
		String enopenid=CookieSecurityUtil.encrypt(openid);
		String phone=JwtOpenidHelper.getPhone(claims);
		logger.info("----------------thirdport openid="+openid+",phone="+phone);
		Map<String,Object> map=customerServiceInterface.insertThirdCarOwner(openid,phone);
		logger.info("----------------thirdport result="+map.get("resultMsg"));
		String u="http://"+dm+"/wx/views/modules/shopping.html?openid="+enopenid;
        return "redirect:"+u;
    }
	@RequestMapping("/parsetoken")
	@ResponseBody
    public String parsetoken(@RequestParam("token") String token){
		Claims claims=JwtOpenidHelper.parseJWT(token);
		if(claims==null){
			return "pase error,may be timeout.";
		}
		String openid=JwtOpenidHelper.getOpenId(claims);
		String phone=JwtOpenidHelper.getPhone(claims);
        return "openid:"+openid+",phone:"+phone;
    }
}
